"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { toast } from "react-hot-toast";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { Globe, Twitter, Send } from "lucide-react";
import type { XLayerToken } from "@/types/xlayer";
import { useXLayerWallet } from "@/hooks/useXLayerWallet";
import { apiClient } from "@/lib/api";
import { CandlestickChart } from "./CandlestickChart";
import { generateCandlestickData } from "../utils/chartData";

interface XLayerTokenDetailModalProps {
  token: XLayerToken;
  isOpen: boolean;
  onClose: () => void;
  onTokenUpdate?: (updatedToken: XLayerToken) => void;
}

const SocialLink = ({
  href,
  icon,
  text,
}: {
  href?: string;
  icon: React.ReactNode;
  text: string;
}) => {
  if (!href) return null;

  // Handle Telegram link
  let finalHref = href;
  if (text === "Telegram" && href && !href.startsWith("http")) {
    finalHref = `https://t.me/${href.replace("@", "")}`;
  }
  // Handle Twitter link
  if (text === "Twitter" && href && !href.startsWith("http")) {
    finalHref = `https://twitter.com/${href.replace("@", "")}`;
  }

  return (
    <a
      href={finalHref}
      target="_blank"
      rel="noopener noreferrer"
      className="flex items-center gap-2 text-sm text-gray-300 hover:text-purple-400 transition-colors"
    >
      {icon}
      <span>{text}</span>
    </a>
  );
};

export function XLayerTokenDetailModal({
  token,
  isOpen,
  onClose,
  onTokenUpdate,
}: XLayerTokenDetailModalProps) {
  const {
    isConnected,
    address,
    balance,
    connect,
    getTokenBalance,
    getUserContribution,
  } = useXLayerWallet();

  const [buyAmount, setBuyAmount] = useState("0.1");
  const [sellAmount, setSellAmount] = useState("");
  const [userTokenBalance, setUserTokenBalance] = useState("0");
  const [userContribution, setUserContribution] = useState("0");
  const [isTrading, setIsTrading] = useState(false);
  const [tradeMode, setTradeMode] = useState<"buy" | "sell">("buy");
  const [isCancelling, setIsCancelling] = useState(false);
  const [isRefunding, setIsRefunding] = useState(false);

  // Chart related state - always use token.tokenPrice as source of truth
  const currentPrice = parseFloat(token.tokenPrice) || 0.00001;
  const [chartData, setChartData] = useState(() =>
    generateCandlestickData(currentPrice, 30)
  );

  // Load user-specific data
  const loadUserData = useCallback(async () => {
    if (!isConnected || !address || !token.tokenAddress) return;

    try {
      const [tokenBalance, contribution] = await Promise.all([
        getTokenBalance(token.tokenAddress, address),
        getUserContribution(token.launchId, address),
      ]);

      setUserTokenBalance(tokenBalance);
      setUserContribution(contribution);
    } catch (error) {
      console.error("Failed to load user data:", error);
    }
  }, [
    isConnected,
    address,
    token.tokenAddress,
    token.launchId,
    getTokenBalance,
    getUserContribution,
  ]);

  useEffect(() => {
    loadUserData();

    // Update chart data when token price changes
    if (token.tokenPrice) {
      const newPrice = parseFloat(token.tokenPrice);
      setChartData(generateCandlestickData(newPrice, 30));
    }
  }, [loadUserData, token.tokenPrice]);

  const calculateTokensReceived = useCallback(() => {
    if (!buyAmount) return "0";
    try {
      const ethAmount = parseFloat(buyAmount);
      return (ethAmount / currentPrice).toFixed(0);
    } catch {
      return "0";
    }
  }, [buyAmount, currentPrice]);

  const getProgressPercentage = () => {
    const raised = parseFloat(token.raisedAmount);
    const target = parseFloat(token.targetAmount);
    return Math.min((raised / target) * 100, 100);
  };

  const getRemainingTime = () => {
    if (token.launched || token.cancelled) return null;

    const now = Date.now();
    const deadline = token.deadline * 1000;

    if (now > deadline) return "已结束";

    return formatDistanceToNow(new Date(deadline), {
      addSuffix: true,
      locale: zhCN,
    });
  };

  const handleBuy = async () => {
    if (!isConnected) {
      toast.error("Please connect your wallet first");
      return;
    }

    if (token.launched) {
      toast.error("Token has been launched on DEX and cannot be traded on the internal market");
      return;
    }

    if (token.cancelled) {
      toast.error("Token has been cancelled and cannot be traded");
      return;
    }

    const amount = parseFloat(buyAmount);
    if (amount <= 0) {
      toast.error("Please enter a valid buy amount");
      return;
    }

    const userBalance = parseFloat(balance);
    if (amount > userBalance) {
      toast.error("Token balance is not sufficient");
      return;
    }

    setIsTrading(true);

    try {
      // Step 1: get transaction data
      toast.loading("Preparing transaction...", { id: "buy-toast" });

      const prepareResult = await apiClient.prepareXLayerBuy(token.launchId, {
        buyerAddress: address!,
        ethAmount: amount,
      });

      if (!prepareResult.success) {
        throw new Error("Failed to prepare transaction");
      }

      // Step 2: sign transaction with wallet
      toast.loading("Please confirm transaction in your wallet...", { id: "buy-toast" });

      // Ensure Ethereum wallet exists
      if (!window.ethereum) {
        throw new Error("Please install MetaMask or other Ethereum wallet");
      }

      // Send transaction to wallet
      const txHash = await window.ethereum.request({
        method: "eth_sendTransaction",
        params: [
          {
            from: address,
            to: prepareResult.transaction.to,
            value: "0x" + BigInt(prepareResult.transaction.value).toString(16),
            data: prepareResult.transaction.data,
            gas: "0x" + BigInt(prepareResult.transaction.gasLimit).toString(16),
          },
        ],
      });
      console.log("Buy transaction submitted:", txHash);

      toast.loading("Transaction submitted, waiting for confirmation...", { id: "buy-toast" });

      // Wait for transaction confirmation and then record contribution
      try {
        // Call backend to confirm and record the transaction
        const confirmResult = await apiClient.confirmXLayerBuy(token.launchId, {
          txHash: txHash as string,
          buyerAddress: address!,
          ethAmount: amount,
        });

        if (confirmResult.success) {
          toast.success(
            `Purchase successful! Obtained ${
              confirmResult.tokensReceived ||
              prepareResult.estimate.tokensToReceive
            } ${token.symbol}`,
            { id: "buy-toast" }
          );

          // The token data will be updated via onTokenUpdate callback
          // which will automatically update the displayed price

          // Fetch latest token data to ensure UI consistency
          try {
            const updatedTokenData = await apiClient.getXLayerToken(token.id);
            if (updatedTokenData && onTokenUpdate) {
              onTokenUpdate(updatedTokenData);
            }
          } catch (error) {
            console.error("Failed to fetch updated token data:", error);
          }
        } else {
          toast.error("Transaction submitted, but failed to record contribution", { id: "buy-toast" });
        }
      } catch (confirmError) {
        console.error("Error confirming transaction:", confirmError);
        toast.success(
          `Purchase successful! Obtained ${prepareResult.estimate.tokensToReceive} ${token.symbol}`,
          { id: "buy-toast" }
        );
        toast.error("Transaction submitted, but failed to record contribution. Please check your wallet and try again.", { id: "buy-toast" });
      }

      setBuyAmount("0.1");

      // Delay updating user data to wait for on-chain state
      setTimeout(() => {
        loadUserData();
      }, 3000);
    } catch (error: unknown) {
      console.error("Buy error:", error);
      let errorMessage = "Purchase process failed";

      if (error instanceof Error) {
        if (error.message.includes("User denied transaction")) {
          errorMessage = "User cancelled the transaction";
        } else {
          errorMessage = error.message;
        }
      }

      toast.error(errorMessage, { id: "buy-toast" });
    } finally {
      setIsTrading(false);
    }
  };

  const handleSell = async () => {
    if (!isConnected) {
      toast.error("Please connect your wallet first");
      return;
    }

    if (token.launched) {
      toast.error("Token has been launched on DEX and cannot be traded on the internal market");
      return;
    }

    if (token.cancelled) {
      toast.error("Token has been cancelled and cannot be traded");
      return;
    }

    const amount = parseFloat(sellAmount);
    if (amount <= 0) {
      toast.error("Please enter a valid sell amount");
      return;
    }

    const userBalance = parseFloat(userTokenBalance);
    if (amount > userBalance) {
      toast.error("Token balance is not sufficient");
      return;
    }

    setIsTrading(true);

    try {
      // Ensure Ethereum wallet exists
      if (!window.ethereum) {
        throw new Error("Please install MetaMask or other Ethereum wallet");
      }

      // Step 1: prepare & send approval transaction
      toast.loading("Preparing approval transaction...", { id: "sell-toast" });

      const approveResult = await apiClient.prepareXLayerApprove(
        token.launchId,
        {
          userAddress: address!,
          tokenAmount: amount,
        }
      );

      if (!approveResult.success) {
        throw new Error("Preparation of approval transaction failed");
      }

      // Send approval transaction
      toast.loading("Please confirm approval transaction in wallet...", { id: "sell-toast" });

      const approveTxHash = await window.ethereum.request({
        method: "eth_sendTransaction",
        params: [
          {
            from: address,
            to: approveResult.transaction.to,
            value: "0x" + BigInt(approveResult.transaction.value).toString(16),
            data: approveResult.transaction.data,
            gas: "0x" + BigInt(approveResult.transaction.gasLimit).toString(16),
          },
        ],
      });
      console.log("Approve transaction submitted:", approveTxHash);

      toast.loading("Approval transaction submitted, waiting for confirmation...", { id: "sell-toast" });

      // Wait a short time for approval confirmation (simplified)
      await new Promise((resolve) => setTimeout(resolve, 3000));

      // Step 2: prepare & send sell transaction
      toast.loading("Preparing sell transaction...", { id: "sell-toast" });

      const prepareResult = await apiClient.prepareXLayerSell(token.launchId, {
        sellerAddress: address!,
        tokenAmount: amount,
      });

      if (!prepareResult.success) {
        throw new Error("Preparation of sell transaction failed");
      }

      // Send sell transaction
      toast.loading("Please confirm sell transaction in wallet...", { id: "sell-toast" });

      const sellTxHash = await window.ethereum.request({
        method: "eth_sendTransaction",
        params: [
          {
            from: address,
            to: prepareResult.transaction.to,
            value: "0x" + BigInt(prepareResult.transaction.value).toString(16),
            data: prepareResult.transaction.data,
            gas: "0x" + BigInt(prepareResult.transaction.gasLimit).toString(16),
          },
        ],
      });
      console.log("Sell transaction submitted:", sellTxHash);

      toast.loading("Sell transaction submitted, waiting for confirmation...", { id: "sell-toast" });

      toast.success(
        `Sell successful! Expected to receive ${prepareResult.estimate.ethToReceive} OKB`,
        { id: "sell-toast" }
      );
      setSellAmount("");

      // The token data will be updated via blockchain events or manual refresh

      // Delay updating user data to wait for both transactions confirmation
      setTimeout(() => {
        loadUserData();
      }, 5000); // 延长到5秒以等待两个交易都确认
    } catch (error: unknown) {
      console.error("Sell error:", error);
      let errorMessage = "Sell process failed";

      if (error instanceof Error) {
        if (error.message.includes("User denied transaction")) {
          errorMessage = "User denied transaction";
        } else if (error.message.includes("insufficient token allowance")) {
          errorMessage = "Token allowance insufficient, please retry";
        } else {
          errorMessage = error.message;
        }
      }

      toast.error(errorMessage, { id: "sell-toast" });
    } finally {
      setIsTrading(false);
    }
  };

  const handleCancelLaunch = async () => {
    if (!isConnected) {
      toast.error("Please connect wallet first");
      return;
    }

    if (token.cancelled) {
      toast.error("Token has been cancelled");
      return;
    }

    if (token.launched) {
      toast.error("Token already launched, cannot cancel");
      return;
    }

    // 检查是否是创建者
    if (token.creator?.toLowerCase() !== address?.toLowerCase()) {
      toast.error("Only creator can cancel launch");
      return;
    }

    setIsCancelling(true);

    try {
      // Ensure Ethereum wallet exists
      if (!window.ethereum) {
        throw new Error("Please install MetaMask or other Ethereum wallet");
      }

      // Step 1: prepare cancel transaction
      toast.loading("Preparing cancel transaction...", { id: "cancel-toast" });

      const prepareResult = await apiClient.prepareXLayerCancel(
        token.launchId,
        {
          creatorAddress: address!,
        }
      );

      if (!prepareResult.success) {
        throw new Error("Refund preparation failed");
      }

      // Step 2: send cancel transaction
      toast.loading("Please confirm cancel transaction in wallet...", { id: "cancel-toast" });

      const txHash = await window.ethereum.request({
        method: "eth_sendTransaction",
        params: [
          {
            from: address,
            to: prepareResult.transaction.to,
            value: "0x" + BigInt(prepareResult.transaction.value).toString(16),
            data: prepareResult.transaction.data,
            gas: "0x" + BigInt(prepareResult.transaction.gasLimit).toString(16),
          },
        ],
      });
      console.log("Cancel transaction submitted:", txHash);

      toast.loading("Cancel transaction submitted, waiting for confirmation...", { id: "cancel-toast" });

      // Wait for transaction confirmation before updating UI
      toast.loading("Waiting for transaction confirmation...", { id: "cancel-toast" });

      // Poll for status update (max 30 seconds)
      let confirmed = false;
      const maxAttempts = 15; // 15 attempts * 2 seconds = 30 seconds max

      for (let attempt = 0; attempt < maxAttempts; attempt++) {
        await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 2 seconds between checks

        try {
          // Sync and check status
          await apiClient.syncXLayerToken(token.id);
          const updatedToken = await apiClient.getXLayerToken(token.id);

          if (updatedToken?.cancelled) {
            confirmed = true;
            break;
          }
        } catch (error) {
          console.warn(`Status check attempt ${attempt + 1} failed:`, error);
        }
      }

      if (confirmed) {
        toast.success("Token launch has been cancelled! Contributors can now request refunds.", {
          id: "cancel-toast",
        });
      } else {
        toast.success("Cancel transaction submitted, status update may take a few minutes.", {
          id: "cancel-toast",
        });
      }

      // Close modal and refresh the page to show updated status
      setTimeout(() => {
        onClose();
        window.location.reload();
      }, 2000);
    } catch (error: unknown) {
      console.error("Cancel error:", error);
      let errorMessage = "Cancel process failed";

      if (error instanceof Error) {
        if (error.message.includes("User denied transaction")) {
          errorMessage = "User cancelled the transaction";
        } else {
          errorMessage = error.message;
        }
      }

      toast.error(errorMessage, { id: "cancel-toast" });
    } finally {
      setIsCancelling(false);
    }
  };

  const handleClaimRefund = async () => {
    if (!isConnected) {
      toast.error("Please connect your wallet first");
      return;
    }

    if (!token.cancelled) {
      toast.error("Only cancelled tokens can request refunds");
      return;
    }

    if (parseFloat(userContribution) <= 0) {
      toast.error("You have no contribution record, cannot request refund");
      return;
    }

    setIsRefunding(true);

    try {
      // Ensure Ethereum wallet exists
      if (!window.ethereum) {
        throw new Error("Please install MetaMask or other Ethereum wallet");
      }

      // Step 1: prepare refund transaction
      toast.loading("Preparing refund transaction...", { id: "refund-toast" });

      const prepareResult = await apiClient.prepareXLayerRefund(
        token.launchId,
        {
          contributorAddress: address!,
        }
      );

      if (!prepareResult.success) {
        // Check if token approval is needed
        if (prepareResult.needsApproval && prepareResult.approvalData) {
          toast.loading("Detected need for token approval, please confirm in wallet...", {
            id: "refund-toast",
          });

          // Step 1a: Approve token transfer first
          const approveParams = {
            from: address!,
            to: prepareResult.approvalData.tokenAddress,
            data:
              "0x095ea7b3" + // approve(address,uint256)
              prepareResult.approvalData.spenderAddress
                .slice(2)
                .padStart(64, "0") +
              BigInt(
                parseFloat(prepareResult.approvalData.requiredAmount) * 1e18
              )
                .toString(16)
                .padStart(64, "0"),
            gas: "0x" + (100000).toString(16), // 100k gas should be enough for approval
          };

          console.log("Submitting token approval:", approveParams);

          const approveTxHash = await window.ethereum.request({
            method: "eth_sendTransaction",
            params: [approveParams],
          });

          console.log("Approval transaction submitted:", approveTxHash);
          toast.loading("Token approval transaction submitted, waiting for confirmation...", {
            id: "refund-toast",
          });

          // Wait a bit for the approval transaction to be mined
          await new Promise((resolve) => setTimeout(resolve, 3000));

          // Now retry the refund preparation
          toast.loading("Retrying refund preparation...", { id: "refund-toast" });

          const retryPrepareResult = await apiClient.prepareXLayerRefund(
            token.launchId,
            {
              contributorAddress: address!,
            }
          );

          if (!retryPrepareResult.success) {
            throw new Error(retryPrepareResult.error || "Refund preparation failed");
          }

          // Use the retry result for the refund transaction
          const refundTxParams: {
            from: string;
            to: string;
            value: string;
            data: string;
            gas: string;
            gasPrice?: string;
          } = {
            from: address!,
            to: retryPrepareResult.transaction!.to,
            value:
              "0x" + BigInt(retryPrepareResult.transaction!.value).toString(16),
            data: retryPrepareResult.transaction!.data,
            gas:
              "0x" +
              BigInt(retryPrepareResult.transaction!.gasLimit).toString(16),
          };

          if (retryPrepareResult.transaction!.gasPrice) {
            refundTxParams.gasPrice =
              "0x" +
              BigInt(retryPrepareResult.transaction!.gasPrice).toString(16);
          }

          toast.loading("Please confirm the refund transaction in your wallet...", { id: "refund-toast" });

          const refundTxHash = await window.ethereum.request({
            method: "eth_sendTransaction",
            params: [refundTxParams],
          });

          console.log("Refund transaction submitted:", refundTxHash);
          toast.loading("Refund transaction submitted, waiting for confirmation...", { id: "refund-toast" });

          // Confirm the refund transaction in the database
          try {
            toast.loading("Confirming refund record...", { id: "refund-toast" });

            await apiClient.confirmXLayerRefund(token.launchId, {
              contributorAddress: address!,
              txHash: refundTxHash,
            });

            const gasFeeInfo = retryPrepareResult.estimate!.estimatedGasFee
              ? ` (estimated gas fee: ${
                  retryPrepareResult.estimate!.estimatedGasFee
                } OKB)`
              : "";
            toast.success(
              `Refund successful! You will receive ${
                retryPrepareResult.estimate!.refundAmount
              } OKB${gasFeeInfo}`,
              { id: "refund-toast" }
            );
          } catch (confirmError) {
            console.warn("Failed to confirm refund in database:", confirmError);
            // Still show success as the blockchain transaction succeeded
            const gasFeeInfo = retryPrepareResult.estimate!.estimatedGasFee
              ? ` (estimated gas fee: ${
                  retryPrepareResult.estimate!.estimatedGasFee
                } OKB)`
              : "";
            toast.success(
              `Refund successful! You will receive ${
                retryPrepareResult.estimate!.refundAmount
              } OKB${gasFeeInfo}`,
              { id: "refund-toast" }
            );
          }
        } else {
          throw new Error(prepareResult.error || "Failed to prepare refund transaction");
        }
      } else {
        // No approval needed, proceed with refund directly
        toast.loading("Please confirm the refund transaction in your wallet...", { id: "refund-toast" });

        // 构建交易参数，包括gasPrice（如果后端提供了的话）
        const txParams: {
          from: string;
          to: string;
          value: string;
          data: string;
          gas: string;
          gasPrice?: string;
        } = {
          from: address!,
          to: prepareResult.transaction!.to,
          value: "0x" + BigInt(prepareResult.transaction!.value).toString(16),
          data: prepareResult.transaction!.data,
          gas: "0x" + BigInt(prepareResult.transaction!.gasLimit).toString(16),
        };

        // 如果后端提供了gasPrice，则添加到交易参数中
        if (prepareResult.transaction!.gasPrice) {
          txParams.gasPrice =
            "0x" + BigInt(prepareResult.transaction!.gasPrice).toString(16);
          console.log(
            "Using custom gas price:",
            prepareResult.transaction!.gasPrice
          );
        }

        const txHash = await window.ethereum.request({
          method: "eth_sendTransaction",
          params: [txParams],
        });
        console.log("Refund transaction submitted:", txHash);

        toast.loading("Refund transaction submitted, awaiting confirmation...", { id: "refund-toast" });

        // Confirm the refund transaction in the database
        try {
          toast.loading("Confirming refund record...", { id: "refund-toast" });

          await apiClient.confirmXLayerRefund(token.launchId, {
            contributorAddress: address!,
            txHash: txHash,
          });

          // 显示退款信息，包括gas费用估算
          const gasFeeInfo = prepareResult.estimate!.estimatedGasFee
            ? ` (estimated gas fee: ${prepareResult.estimate!.estimatedGasFee} OKB)`
            : "";
          toast.success(
            `Refund successful! You will receive ${
              prepareResult.estimate!.refundAmount
            } OKB${gasFeeInfo}`,
            { id: "refund-toast" }
          );
        } catch (confirmError) {
          console.warn("Failed to confirm refund in database:", confirmError);
          // Still show success as the blockchain transaction succeeded
          const gasFeeInfo = prepareResult.estimate!.estimatedGasFee
            ? ` (estimated gas fee: ${prepareResult.estimate!.estimatedGasFee} OKB)`
            : "";
          toast.success(
            `Refund transaction completed! You will receive ${
              prepareResult.estimate!.refundAmount
            } OKB${gasFeeInfo}`,
            { id: "refund-toast" }
          );
        }
      }

      // Update user data
      setTimeout(() => {
        loadUserData();
      }, 3000);
    } catch (error: unknown) {
      console.error("Refund error:", error);
      let errorMessage = "Refund process failed";

      if (error instanceof Error) {
        if (error.message.includes("User denied transaction")) {
          errorMessage = "User cancelled the transaction";
        } else {
          errorMessage = error.message;
        }
      }

      toast.error(errorMessage, { id: "refund-toast" });
    } finally {
      setIsRefunding(false);
    }
  };

  const getStatusBadge = () => {
    if (token.cancelled) {
      return (
        <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-red-400 text-black border-2 border-black">
          cancelled
        </span>
      );
    }
    if (token.launched) {
      return (
        <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-green-400 text-black border-2 border-black">
          launched
        </span>
      );
    }
    if (Date.now() > token.deadline * 1000) {
      return (
        <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-gray-400 text-black border-2 border-black">
          deadline
        </span>
      );
    }
    return (
      <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-blue-400 text-black border-2 border-black">
        active
      </span>
    );
  };

  return (
    <>
      {/* Overlay */}
      <div
        className={`fixed inset-0 bg-black/60 transition-opacity duration-300 z-[100] ${
          isOpen
            ? "opacity-100 pointer-events-auto"
            : "opacity-0 pointer-events-none"
        }`}
        onClick={onClose}
      />

      {/* Right Drawer */}
      <div
        className={`pixel-modal fixed top-0 right-0 h-full w-[90vw] md:w-[520px] lg:w-[560px] shadow-2xl z-[110] transform transition-transform duration-300 ease-in-out ${
          isOpen ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Header */}
          <div className="flex justify-between items-center p-5 md:p-6 border-b border-gray-600">
            <h2 className="text-xl font-bold font-pixel">XLayer</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-white transition-colors"
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>

          {/* Content */}
          <div className="flex-grow p-6 md:p-8 pt-8 md:pt-10 overflow-y-auto space-y-8">
            {/* Token Info */}
            <div className="flex items-start gap-6">
              {token.imageUrl ? (
                <Image
                  src={token.imageUrl}
                  alt={token.name}
                  width={64}
                  height={64}
                  className="object-cover"
                  style={{ imageRendering: "pixelated" }}
                />
              ) : (
                <div
                  className="w-16 h-16 bg-gradient-to-br from-purple-500 to-indigo-600 flex items-center justify-center"
                  style={{ imageRendering: "pixelated" }}
                >
                  <span className="text-white font-bold text-2xl font-pixel">
                    {token.symbol.charAt(0)}
                  </span>
                </div>
              )}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="text-2xl font-bold truncate font-body">
                    {token.name}
                  </h3>
                  {getStatusBadge()}
                </div>
                <p className="text-sm text-gray-400 font-mono">
                  {token.symbol}
                </p>
                <div className="flex items-center gap-2 mt-1">
                  <p className="text-xs text-gray-500 font-mono truncate">
                    {token.tokenAddress}
                  </p>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(token.tokenAddress);
                      toast.success("已复制到剪贴板");
                    }}
                    className="text-gray-400 hover:text-white"
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                      />
                    </svg>
                  </button>
                  <a
                    href={`https://www.oklink.com/zh-hans/x-layer/address/${token.tokenAddress}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-400 hover:text-white"
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                      />
                    </svg>
                  </a>
                </div>
              </div>
            </div>

            {/* Stats */}
            <div className="pixel-card p-5 md:p-6 space-y-4">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-400">price</span>
                <span className="text-sm font-medium text-white font-mono">
                  {currentPrice.toFixed(8)} OKB
                </span>
              </div>
              {token.marketCap && (
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-400">TVL</span>
                  <span className="text-sm font-medium text-white font-mono">
                    {parseFloat(token.marketCap).toFixed(2)} OKB
                  </span>
                </div>
              )}
              {token.holders !== undefined && (
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-400">Holder</span>
                  <span className="text-sm font-medium text-white font-mono">
                    {token.holders}
                  </span>
                </div>
              )}

              {/* Basic Info */}
              <div className="border-t border-gray-700 pt-3 mt-3">
                <div className="text-sm text-gray-400 mb-2">Basic Info</div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-400">Creator</span>
                  <span className="text-sm font-medium text-white font-mono truncate ml-2">
                    {token.creator?.slice(0, 6)}...{token.creator?.slice(-4)}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-400">Creation Time</span>
                  <span className="text-sm font-medium text-white font-mono">
                    {new Date(token.createdAt * 1000).toLocaleDateString()}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-400">Target Funding</span>
                  <span className="text-sm font-medium text-white font-mono">
                    {token.targetAmount} OKB
                  </span>
                </div>
              </div>

              {/* User Balance */}
              {isConnected &&
                (parseFloat(userTokenBalance) >= 0 ||
                  parseFloat(userContribution) >= 0) && (
                  <div className="border-t border-gray-700 pt-3 mt-3">
                    <div className="text-sm text-gray-400 mb-2">My Holdings</div>

                    {/* Debug Info - Show connected wallet address */}
                    <div className="flex justify-between items-center text-xs">
                      <span className="text-xs text-gray-500">Wallet Address</span>
                      <span className="text-xs font-mono text-gray-500">
                        {address
                          ? `${address.slice(0, 6)}...${address.slice(-4)}`
                          : "Not connected"}
                      </span>
                    </div>

                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Token Amount</span>
                      <span className="text-sm font-medium text-white font-mono">
                        {parseFloat(userTokenBalance).toLocaleString()}{" "}
                        {token.symbol}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">OKB Balance</span>
                      <span className="text-sm font-medium text-white font-mono">
                        {parseFloat(balance).toFixed(6)} OKB
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Total Contribution</span>
                      <span className="text-sm font-medium text-white font-mono">
                        {userContribution} OKB
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Token Value</span>
                      <span className="text-sm font-medium text-white font-mono">
                        ≈{" "}
                        {(parseFloat(userTokenBalance) * currentPrice).toFixed(
                          6
                        )}{" "}
                        OKB
                      </span>
                    </div>
                  </div>
                )}
            </div>

            {/* Launch Progress */}
            {!token.launched && !token.cancelled && (
              <div className="pixel-card p-5 md:p-6">
                <h4 className="text-md font-semibold mb-4 font-pixel">
                  Fundraising progress
                </h4>
                <div className="text-xs text-gray-400 mb-3 font-mono">
                  💡 Token is currently in the bonding curve and will be
                  launched on the DEX once the fundraising goal is reached.
                </div>
                <div className="flex justify-between text-sm mb-2 font-mono">
                  <span className="text-gray-400">Progress</span>
                  <span className="text-white">
                    {getProgressPercentage().toFixed(1)}%
                  </span>
                </div>
                <div className="w-full bg-gray-600 h-3 mb-3 pixel-border">
                  <div
                    className="bg-green-400 h-3 transition-all"
                    style={{
                      width: `${getProgressPercentage()}%`,
                      imageRendering: "pixelated",
                    }}
                  />
                </div>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-400 font-mono">
                      Amount Raised:
                    </span>
                    <div className="font-semibold text-white font-mono">
                      {token.raisedAmount} OKB
                    </div>
                  </div>
                  <div>
                    <span className="text-gray-400 font-mono">Target:</span>
                    <div className="font-semibold text-white font-mono">
                      {token.targetAmount} OKB
                    </div>
                  </div>
                  <div>
                    <span className="text-gray-400 font-mono">
                      Token Price:
                    </span>
                    <div className="font-semibold text-white font-mono">
                      {token.tokenPrice} OKB
                    </div>
                  </div>
                  <div>
                    <span className="text-gray-400 font-mono">
                      Remaining Quota:
                    </span>
                    <div className="font-semibold text-white font-mono">
                      {(
                        parseFloat(token.targetAmount) -
                        parseFloat(token.raisedAmount)
                      ).toFixed(4)}{" "}
                      OKB
                    </div>
                  </div>
                </div>
                {getRemainingTime() && (
                  <div className="flex justify-between items-center mt-3 pt-3 border-t border-gray-700">
                    <span className="text-gray-400 font-mono">
                      Remaining Time:
                    </span>
                    <span className="font-medium text-white font-mono">
                      {getRemainingTime()}
                    </span>
                  </div>
                )}
              </div>
            )}

            {/* Chart */}
            <div className="pixel-card p-5 md:p-6">
              <CandlestickChart data={chartData} />
            </div>

            {/* Social Links */}
            {(token.website || token.telegram || token.twitter) && (
              <div className="pixel-card p-5 md:p-6 space-y-4">
                <h4 className="text-md font-semibold mb-2 font-pixel">
                  Social Links
                </h4>
                <div className="flex flex-wrap items-center gap-3 md:gap-4">
                  <SocialLink
                    href={token.website}
                    icon={<Globe size={16} />}
                    text="Website"
                  />
                  <SocialLink
                    href={token.twitter}
                    icon={<Twitter size={16} />}
                    text="Twitter"
                  />
                  <SocialLink
                    href={token.telegram}
                    icon={<Send size={16} />}
                    text="Telegram"
                  />
                </div>
              </div>
            )}

            {/* Description */}
            {token.description && (
              <div className="pixel-card p-5 md:p-6">
                <h4 className="text-md font-semibold mb-2 font-pixel">
                  Description
                </h4>
                <p className="text-sm text-gray-300 font-body">
                  {token.description}
                </p>
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="p-6 md:p-8 border-t border-gray-700 space-y-5">
            {token.cancelled ? (
              // Cancelled token panel
              <div className="space-y-4">
                <div className="text-center py-8">
                  <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="flex items-center space-x-2 mb-2">
                      <span className="text-2xl">❌</span>
                      <h4 className="text-lg font-semibold text-red-800">
                        Tokens cancelled
                      </h4>
                    </div>
                    <p className="text-red-700 text-sm font-mono">
                      The token sale has been canceled and is no longer
                      available for trading.
                    </p>
                  </div>
                </div>

                {/* Refund button for contributors */}
                {isConnected && parseFloat(userContribution) > 0 && (
                  <button
                    onClick={handleClaimRefund}
                    disabled={isRefunding}
                    className="pixel-btn w-full text-lg font-bold bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isRefunding
                      ? "Requesting Refund..."
                      : `Request Refund (${userContribution} OKB)`}
                  </button>
                )}

                {!isConnected && (
                  <button
                    onClick={connect}
                    className="pixel-btn w-full text-lg font-bold bg-purple-600 hover:bg-purple-700"
                  >
                    Connect Wallet to Request Refund
                  </button>
                )}
              </div>
            ) : token.launched ? (
              // Launched token - show DEX trading info
              <div className="text-center py-8">
                <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-4">
                  <div className="flex items-center space-x-2 mb-2">
                    <span className="text-2xl">🚀</span>
                    <h4 className="text-lg font-semibold text-green-800">
                      Tokens launched on DEX
                    </h4>
                  </div>
                  <p className="text-green-700 text-sm font-mono mb-4">
                    The token has been successfully launched on the
                    decentralized exchange after completing the fundraising
                    phase.
                  </p>
                  <div className="space-y-2">
                    <p className="text-green-600 text-xs font-mono">
                      💡 You can now trade on external DEX
                    </p>
                    <a
                      href={`https://potatoswap.finance/swap?inputCurrency=${token.tokenAddress}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center px-4 py-2 bg-purple-600 text-white text-sm font-medium rounded-lg hover:bg-purple-700 transition-colors pixel-btn"
                    >
                       potatoswap
                      <svg
                        className="ml-2 w-4 h-4"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                    </a>
                  </div>
                </div>
              </div>
            ) : (
              // In-progress token - internal bonding curve trading
              <>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
                  <div className="flex items-center space-x-2 mb-1">
                    <span className="text-lg">💰</span>
                    <h5 className="text-sm font-semibold text-blue-800">
                      Internal trading in progress
                    </h5>
                  </div>
                  <p className="text-blue-700 text-xs font-mono">
                    The token is currently in the fundraising phase and can
                    participate in Buy/Sell trades. Once 100% is reached, it
                    will be automatically launched on DEX.
                  </p>
                </div>

                {/* Cancel launch button for creator */}
                {isConnected &&
                  token.creator?.toLowerCase() === address?.toLowerCase() && (
                    <div className="mb-4">
                      <button
                        onClick={handleCancelLaunch}
                        disabled={isCancelling}
                        className="pixel-btn w-full text-lg font-bold bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {isCancelling ? "cancelling..." : "Cancel Launch (Creator)"}
                      </button>
                      <p className="text-red-400 text-xs font-mono mt-2">
                        ⚠️ Cancelling will allow all contributors to request refunds. This action is irreversible.
                      </p>
                    </div>
                  )}

                <div className="flex bg-gray-800 p-2 gap-2">
                  <button
                    onClick={() => setTradeMode("buy")}
                    className={`pixel-btn flex-1 text-md font-bold transition-colors ${
                      tradeMode === "buy"
                        ? "bg-green-600 text-white"
                        : "bg-gray-600 hover:bg-gray-500"
                    }`}
                  >
                    Buy
                  </button>
                  <button
                    onClick={() => setTradeMode("sell")}
                    className={`pixel-btn flex-1 text-md font-bold transition-colors ${
                      tradeMode === "sell"
                        ? "bg-red-600 text-white"
                        : "bg-gray-600 hover:bg-gray-500"
                    }`}
                  >
                    Sell
                  </button>
                </div>

                <div className="relative mt-2">
                  <input
                    type="number"
                    value={tradeMode === "buy" ? buyAmount : sellAmount}
                    onChange={(e) =>
                      tradeMode === "buy"
                        ? setBuyAmount(e.target.value)
                        : setSellAmount(e.target.value)
                    }
                    placeholder={`input ${
                      tradeMode === "buy"
                        ? "OKB amount"
                        : `${token.symbol} token amount`
                    }`}
                    className="w-full px-3 py-2 bg-gray-800 border-2 border-gray-600 text-white placeholder-gray-400 font-mono focus:border-purple-400 focus:outline-none"
                    style={{ imageRendering: "pixelated" }}
                  />
                  <div className="absolute right-3 top-1/2 transform -translate-y-1/2 text-sm text-gray-400">
                    {tradeMode === "buy" ? "OKB" : token.symbol}
                  </div>
                </div>

                {/* Balance display & Max button */}
                {isConnected && tradeMode === "sell" && (
                  <div className="flex justify-between items-center text-sm text-gray-400 mt-2">
                    <span>
                      Number of available tokens:{" "}
                      {parseFloat(userTokenBalance).toLocaleString()}{" "}
                      {token.symbol}
                    </span>
                    {parseFloat(userTokenBalance) > 0 && (
                      <button
                        type="button"
                        onClick={() => setSellAmount(userTokenBalance)}
                        className="text-purple-400 hover:text-purple-300 transition-colors"
                      >
                        Max
                      </button>
                    )}
                  </div>
                )}

                {/* Expected tokens to receive */}
                {tradeMode === "buy" && buyAmount && (
                  <div className="pixel-card p-3">
                    <div className="text-sm text-gray-400 mb-1 font-mono">
                      Expected to receive
                    </div>
                    <div className="text-lg font-semibold text-green-400 font-mono">
                      {calculateTokensReceived()} {token.symbol}
                    </div>
                  </div>
                )}

                {!isConnected ? (
                  <button
                    onClick={connect}
                    className="pixel-btn w-full text-lg font-bold bg-purple-600 hover:bg-purple-700"
                  >
                    Connect Wallet
                  </button>
                ) : (
                  <button
                    onClick={tradeMode === "buy" ? handleBuy : handleSell}
                    disabled={
                      isTrading ||
                      (tradeMode === "buy"
                        ? !buyAmount || parseFloat(buyAmount) <= 0
                        : !sellAmount || parseFloat(sellAmount) <= 0)
                    }
                    className={`pixel-btn w-full text-lg font-bold transition-colors ${
                      tradeMode === "buy"
                        ? "bg-green-600 hover:bg-green-700"
                        : "bg-red-600 hover:bg-red-700"
                    } disabled:opacity-50 disabled:cursor-not-allowed`}
                  >
                    {isTrading
                      ? "trading..."
                      : tradeMode === "buy"
                      ? "Buy"
                      : "Sell"}
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
